package com.ahdy.mapper;

import com.ahdy.entity.DailyMedicationTask;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

// 7. 每日用药任务Mapper
@Mapper
public interface DailyMedicationTaskMapper {

    @Insert("INSERT INTO daily_medication_tasks(plan_id, user_id, medication_id, task_date, timing_type, " +
            "scheduled_time, dosage, status, created_at) VALUES(#{planId}, #{userId}, #{medicationId}, " +
            "#{taskDate}, #{timingType}, #{scheduledTime}, #{dosage}, #{status}, #{createdAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(DailyMedicationTask task);

    @Update("UPDATE daily_medication_tasks SET status=#{status} WHERE id=#{id}")
    int updateStatus(@Param("id") Integer id, @Param("status") DailyMedicationTask.TaskStatus status);

    @Delete("DELETE FROM daily_medication_tasks WHERE id=#{id}")
    int deleteById(Integer id);

    @Select("SELECT * FROM daily_medication_tasks WHERE id=#{id}")
    DailyMedicationTask findById(Integer id);

    @Select("SELECT * FROM daily_medication_tasks WHERE user_id=#{userId} AND task_date=#{taskDate} ORDER BY scheduled_time ASC")
    List<DailyMedicationTask> findByUserIdAndDate(@Param("userId") Integer userId, @Param("taskDate") LocalDate taskDate);

    @Select("SELECT * FROM daily_medication_tasks WHERE user_id=#{userId} AND task_date BETWEEN #{startDate} AND #{endDate} ORDER BY task_date DESC, scheduled_time ASC")
    List<DailyMedicationTask> findByUserIdAndDateRange(@Param("userId") Integer userId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    @Select("SELECT * FROM daily_medication_tasks WHERE task_date=#{taskDate} AND status='未服用' ORDER BY scheduled_time ASC")
    List<DailyMedicationTask> findUncompletedByDate(LocalDate taskDate);

    @Delete("DELETE FROM daily_medication_tasks WHERE user_id=#{userId}")
    int deleteByUserId(Integer userId);

    @Delete("DELETE FROM daily_medication_tasks WHERE plan_id=#{planId}")
    int deleteByPlanId(Integer planId);

    // 批量插入任务
    int batchInsert(List<DailyMedicationTask> tasks);

    // 获取今日用药任务统计
    Map<String, Object> getTodayTaskStatistics(Integer userId);

    // 获取需要提醒的任务
    List<DailyMedicationTask> findTasksNeedingReminder(@Param("date") LocalDate date, @Param("currentTime") String currentTime);

    // 获取延迟服药任务（用于通知家属）
    List<Map<String, Object>> findDelayedTasksForNotification(@Param("date") LocalDate date, @Param("delayMinutes") Integer delayMinutes);
}
